package com.kmxd.ams.core.util;

import cn.easyes.core.biz.EsPageInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import org.apache.commons.compress.utils.Lists;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 转换类
 *
 * @author nickbi
 */
public class ConvertUtil {
  private ConvertUtil() {}

  public static <T> T toBean(Object source, Class<T> clazz) {
    return BeanUtil.copyProperties(source, clazz);
  }

  public static <T> List<T> toList(List<?> sourceList, Class<T> clazz) {
    return BeanUtil.copyToList(sourceList, clazz);
  }

  public static List<Map<String, Object>> toList(List<?> sourceList) {
    if (ObjectUtil.isEmpty(sourceList)) {
      return Lists.newArrayList();
    }
    return sourceList.stream().map(BeanUtil::beanToMap).collect(Collectors.toList());
  }

  public static <T> Page<T> toPage(Page<?> sourcePage, Class<T> clazz) {
    Page<T> page = new Page<>();
    page.setSize(sourcePage.getSize());
    page.setTotal(sourcePage.getTotal());
    page.setCurrent(sourcePage.getCurrent());
    page.setRecords(
        sourcePage.getRecords().stream().map(s -> toBean(s, clazz)).collect(Collectors.toList()));
    return page;
  }

  public static <T> Page<T> toPage(EsPageInfo<?> sourcePage, Class<T> clazz) {
    Page<T> page = new Page<>();
    page.setSize(sourcePage.getSize());
    page.setTotal(sourcePage.getTotal());
    page.setCurrent(sourcePage.getPageNum());
    page.setRecords(
        sourcePage.getList().stream().map(s -> toBean(s, clazz)).collect(Collectors.toList()));
    return page;
  }

  public static <T> T toMetaFieldBean(
      Object source, Map<String, String> metaFieldMap, Class<T> clazz) {
    Map<String, Object> sourceMap = BeanUtil.beanToMap(source);
    Map<String, Object> targetMap = Maps.newHashMap();
    metaFieldMap.forEach((key, value) -> {
      String copyField = StringUtils.underlineToCamel(value);
      String valueField = StringUtils.underlineToCamel(key);
      targetMap.put(copyField, sourceMap.get(valueField));
    });
    return BeanUtil.toBean(targetMap, clazz);
  }

  public static <T> List<T> getListValue(Object source, String field, Class<T> clazz) {
    JSONObject jsonObject = JSONUtil.parseObj(source);
    String objectStr = jsonObject.getStr(field);
    return JSONUtils.toList(objectStr, clazz);
  }

  public static <T> T getValue(Object source, String field, Class<T> clazz) {
    JSONObject jsonObject = JSONUtil.parseObj(source);
    return jsonObject.get(field, clazz);
  }
}
